package com.web.kdl.service.send;
import com.web.kdl.util.TopicUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class MqttServiceImpl implements MqttService{

    @Autowired
    @Qualifier("mqttProducerClient") // 指定注入生产者客户端
    private MqttClient mqttClient;

    @Value("${custom-mqtt.producer.defaultTopic}")
    private String defaultTopic;

    /**
     * 发送十六进制数据到MQTT主题
     */
    public void sendHexData(String hexString) {
        try {
            // 1. 转换十六进制字符串为字节数组
            byte[] payload = hexToBytes(hexString.replaceAll("\\s+", ""));

            // 2. 创建消息并设置QoS
            MqttMessage message = new MqttMessage(payload);
            message.setQos(1);

            // 3. 发布到默认主题
            mqttClient.publish(defaultTopic,message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendHexData(String hexString, String topic) {
        try {
            // 1. 转换十六进制字符串为字节数组
            byte[] payload = hexToBytes(hexString.replaceAll("\\s+", ""));

            // 2. 创建消息并设置QoS
            MqttMessage message = new MqttMessage(payload);
            message.setQos(1);

            // 3. 发布到默认主题
            String publishTopic = TopicUtils.getPublishTopic(topic);
            mqttClient.publish(publishTopic,message);
        } catch (Exception e) {
            // 👉 判断是不是因为程序关闭导致的中断
            if (e.getCause() instanceof InterruptedException) {
                System.out.println("程序关闭中，MQTT 发送线程被中断，正常退出。");
            } else {
                System.err.println("MQTT 发送异常：" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 将16进制字符串转换为字节数组
     */
    private byte[] hexToBytes(String hex) {
        if (hex == null || hex.length() % 2 != 0) {
            throw new IllegalArgumentException("Invalid hex string");
        }
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < hex.length(); i += 2) {
            String byteStr = hex.substring(i, i + 2);
            bytes[i / 2] = (byte) Integer.parseInt(byteStr, 16);
        }
        return bytes;
    }
}